<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['travel:consult:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['travel:consult:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleAdd" v-hasPermi="['travel:consult:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleAdd" v-hasPermi="['travel:consult:add']">导入模板下载</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-user"
          size="mini"
          @click="openDesignerDialog()"
          v-if="showAssignDesignerButton()"
          :disabled="multiple"
        >
          分配定制师
        </el-button>
      </el-col>

      <el-col :span="2">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh-left"
          size="mini"
          @click="handlerReject()"
          v-if="showReject1Button()"
          :disabled="multiple"
        >
          退回
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="clientName">
        <el-input
          v-model="queryParams['travelClient.clientName']"
          placeholder="输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="手机号" prop="travelClient">
        <el-input
          v-model="queryParams['travelClient.clientTel']"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="consultList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="序号" align="center" prop="consultId" type="index"/>-->
      <el-table-column label="序号" align="center" width="60">
        <template slot-scope="scope">
          <!-- 公式：(当前页-1) * 每页条数 + 当前行索引 + 1 -->
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="咨询号" align="center" prop="consultNumber" width="170"/>
      <el-table-column label="客户姓名" align="center" prop="travelClient.clientName" />
      <el-table-column label="手机号" align="center" prop="travelClient.clientTel" width="110"/>
      <el-table-column label="出行人数" align="center" prop="travelerCount" />
      <el-table-column label="意向目的地" align="center" prop="preferredDestination"/>
      <el-table-column label="预计出发时间" align="center" prop="estimatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.estimatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="可调整时间范围" align="center" prop="flexibleDays" />
      <el-table-column label="计划天数" align="center" prop="plannedDays" />
      <el-table-column label="预算" align="center" prop="budget" />
      <el-table-column label="定制师" align="center" prop="designerId" >
        <template slot-scope="scope">
          {{ scope.row.designerName || '未分配' }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="showEditButton(scope.row)"
          >修改</el-button>
          <!-- 操作列退回按钮：传递当前行的consultId -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="handlerReject(scope.row.consultId)"
            v-if="showRejectButton(scope.row)"
          >退回</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="openDesignerDialog(scope.row.consultId)"
            v-if="showAssignDesigner1Button(scope.row)"
          >定制师</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改咨询管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="客户姓名" prop="clientName">
          <el-row :gutter="8">
            <el-col :span="15">
              <el-input
                v-model="form.clientName"
                placeholder="请选择客户"
                :disabled="true"
              />
            </el-col>
            <el-col :span="6.5" style="margin-left: 16px;">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="openUserDialog"
                :disabled="isEdit"
              >选择客户</el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="客户手机号" prop="clientTel">
          <el-input
            v-model="form.clientTel"
            placeholder="客户手机号"
            :disabled="true"
            style="width: 400px;"
          />
        </el-form-item>

        <el-form-item label="出行人数" prop="travelerCount">
          <el-input
            v-model.number="form.travelerCount"
            placeholder="请输入大于0的整数"
            :disabled="!isUserSelected"
            style="width: 400px;"
          />
        </el-form-item>

        <el-form-item label="意向目的地" prop="preferredDestination">
          <el-input
            v-model="form.preferredDestination"
            placeholder="请输入意向目的地"
            :disabled="!isUserSelected"
            style="width: 400px;"
          />
        </el-form-item>

        <el-form-item label="预计出发时间" prop="estimatedTime">
          <el-date-picker
            clearable
            v-model="form.estimatedTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预计出发时间"
            :disabled="!isUserSelected"
            style="width: 400px;"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="可调整时间范围" prop="flexibleDays">
          <el-input
            v-model="form.flexibleDays"
            placeholder="格式示例: 前3后2、前3、后2"
            :disabled="!isUserSelected"
            style="width: 400px;"
          />
        </el-form-item>

        <el-form-item label="计划天数" prop="plannedDays">
          <el-input
            v-model.number="form.plannedDays"
            placeholder="请输入大于0的整数"
            :disabled="!isUserSelected"
            style="width: 400px;"
          />
        </el-form-item>

        <el-form-item label="预算" prop="budget">
          <el-input
            v-model.number="form.budget"
            placeholder="请输入数字，可保留两位小数"
            :disabled="!isUserSelected"
            style="width: 400px;"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注（选填）"
            :disabled="!isUserSelected"
            style="width: 400px;"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitForm"
          :disabled="!isUserSelected"
        >
          确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户选择对话框 -->
    <el-dialog
      title="选择客户"
      :visible.sync="userDialogVisible"
      width="700px"
      append-to-body
    >
      <el-form
        :model="clientQueryParams"
        ref="userQueryForm"
        size="small"
        :inline="true"
        label-width="60px"
        class="mb10"
      >
        <el-form-item label="客户姓名">
          <el-input
            v-model="clientQueryParams.clientName"
            placeholder="请输入姓名"
            clearable
            @keyup.enter.native="getClientList"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="clientQueryParams.clientTel"
            placeholder="请输入手机号"
            clearable
            @keyup.enter.native="getClientList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getClientList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetClientQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 客户列表（修改为单选框模式） -->
      <el-table
        ref="userTable"
        v-loading="clientLoading"
        :data="clientList"
        highlight-current-row
        @current-change="handleUserCurrentChange"
        @row-click="handleUserRowClick"
        border
      >
        <!-- 单选框列 -->
        <el-table-column width="55" align="center">
          <template slot-scope="scope">
            <el-radio
              class="radio"
              :label="scope.row"
              v-model="selectedUser"
            >{{ "" }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="姓名" prop="clientName" align="center" />
        <el-table-column label="手机号" prop="clientTel" align="center" />
        <el-table-column label="备注" prop="remark" align="center" />
      </el-table>

      <pagination
        v-show="clientTotal > 0"
        :total="clientTotal"
        :page.sync="clientQueryParams.pageNum"
        :limit.sync="clientQueryParams.pageSize"
        @pagination="getClientList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUserSelection" :disabled="!selectedUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配定制师对话框 -->
    <el-dialog
      title="分配定制师"
      :visible.sync="designerDialogVisible"
      width="700px"
      append-to-body
    >
      <el-form
        :model="designerQueryParams"
        ref="designerQueryForm"
        size="small"
        :inline="true"
        label-width="60px"
        class="mb10"
      >
        <el-form-item label="姓名">
          <el-input
            v-model="designerQueryParams.nickName"
            placeholder="请输入定制师姓名"
            clearable
            @keyup.enter.native="getDesignerList"
          />
        </el-form-item>

        <el-form-item label="手机号">
          <el-input
            v-model="designerQueryParams.phonenumber"
            placeholder="请输入定制师手机号"
            clearable
            @keyup.enter.native="getDesignerList"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getDesignerList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetDesignerQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 定制师列表（修改为单选框模式） -->
      <el-table
        ref="designerTable"
        v-loading="designerLoading"
        :data="designerList"
        highlight-current-row
        @current-change="handleDesignerCurrentChange"
        @row-click="handleDesignerRowClick"
        border
      >
        <!-- 单选框列 -->
        <el-table-column width="55" align="center">
          <template slot-scope="scope">
            <el-radio
              class="radio"
              :label="scope.row"
              v-model="selectedDesigner"
            >{{ "" }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="姓名" prop="nickName" align="center" />
        <el-table-column label="手机号" prop="phonenumber" align="center" />
      </el-table>

      <pagination
        v-show="designerTotal > 0"
        :total="designerTotal"
        :page.sync="designerQueryParams.pageNum"
        :limit.sync="designerQueryParams.pageSize"
        @pagination="getDesignerList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="designerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDesignerAssignment" :disabled="!selectedDesigner">确认分配</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConsult, getConsult, delConsult, addConsult, updateConsult, assignDesigner } from "@/api/travel/consult";
import { listClient } from '@/api/travel/client'
import { listUser, listRoleUser, getUserProfile } from '@/api/system/user'

export default {
  name: "Consult",
  dicts: ['sys_user_sex'],
  computed: {
    isUserSelected() {
      return !!this.form.clientId || (this.isEdit && !!this.form.clientName)
    }
  },
  data() {

    const validateFlexibleDays = (rule, value, callback) => {
      if (!value) return callback();
      const reg = /^(前\d+后\d+)|(前\d+)|(后\d+)$/;
      reg.test(value) ? callback() : callback(new Error('格式不正确，请使用"前3后2"、"前3"或"后2"格式'));
    };

    const validateBudget = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') return callback(new Error('请输入预算'));
      const reg = /^\d+(\.\d{1,2})?$/;
      reg.test(value) ? callback() : callback(new Error('请输入有效的数字，最多保留两位小数'));
    };

    const validatePositiveInteger = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') return callback(new Error('请输入数值'));
      const reg = /^[1-9]\d*$/;
      reg.test(value) ? callback() : callback(new Error('请输入大于0的整数'));
    };

    return {
      clientLoading:false,
      clientTotal:0,
      designerIdsArray: [],
      currentAssignIds: [], // 存储当前需要分配的咨询ID（单个/批量）
      currentRejectIds: [], // 存储当前需要退回的咨询ID（单个/批量）
      currentUserId: null,
      currentUserRoleName: '',
      loading: true,
      userLoading: false,
      designerLoading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      userTotal: 0,
      designerTotal: 0,
      consultList: [],
      clientList: [],
      userList: [],
      designerList: [],
      title: "",
      open: false,
      userDialogVisible: false,
      designerDialogVisible: false,
      isEdit: false,
      selectedUser: null,
      selectedDesigner: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        consultNumber: null,
        clientId: null,
        travelerCount: null,
        preferredDestination: null,
        estimatedTime: null,
        flexibleDays: null,
        plannedDays: null,
        budget: null,
        designerId: null,
        userId: this.currentUserId,  //userId放入查询参数里面
        userRoleName: this.currentUserRoleName,
      },
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        phonenumber: null
      },
      clientQueryParams: {
        pageNum: 1,
        pageSize: 10,
        clientName: null,
        clientTel: null
      },

      designerQueryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        phonenumber: null,
        "roles[0].roleName": '定制师'
      },
      form: {
        consultId: null,
        consultNumber: null,
        clientId: null,
        clientName: null,
        clientTel: null,
        travelerCount: null,
        preferredDestination: null,
        estimatedTime: null,
        flexibleDays: null,
        plannedDays: null,
        budget: null,
        designerId: null,
        remark: null
      },
      rules: {
        clientName: [{ required: true, message: "请选择客户", trigger: "blur" }],
        clientTel: [{ required: true, message: "客户手机号不能为空", trigger: "blur" }],
        travelerCount: [
          { required: true, message: "请输入出行人数", trigger: "blur" },
          { validator: validatePositiveInteger, trigger: "blur" }
        ],
        preferredDestination: [{ required: true, message: "请输入意向目的地", trigger: "blur" }],
        estimatedTime: [{ required: true, message: "请选择预计出发时间", trigger: "change" }],
        flexibleDays: [{ validator: validateFlexibleDays, trigger: "blur" }],
        plannedDays: [
          { required: true, message: "请输入计划天数", trigger: "blur" },
          { validator: validatePositiveInteger, trigger: "blur" }
        ],
        budget: [
          { required: true, message: "请输入预算", trigger: "blur" },
          { validator: validateBudget, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getUserInfo()
    this.getClientList();
    this.getDesignerList();
  },
  methods: {


    getUserInfo() {
      try {
        getUserProfile().then(userProfileRes => {
          console.log(userProfileRes)
          // 保存当前用户的 userId 到变量中
          this.currentUserId = userProfileRes.data.userId
          this.currentUserRoleName = userProfileRes.data.roles[0].roleName
          console.log(userProfileRes.data.roles[0].roleName)

          // 2. 给 queryParams 赋值（关键：在异步请求完成后再赋值）
          this.queryParams.userId = this.currentUserId
          this.queryParams.userRoleName = this.currentUserRoleName

          // 3. 调用 getList 加载数据（此时参数已正确赋值）
          this.getList()
        })
      } catch (error) {
        console.error('获取当前用户信息失败：', error)
        this.$message.error('获取用户信息失败，请刷新页面重试')
      }
    },
    // 1. 核心修改：获取定制师列表并提取ID到数组
    getDesignerList() {
      this.designerLoading = true;
      listRoleUser(this.designerQueryParams)
        .then(response => {
          this.designerList = response.rows || [];
          this.designerTotal = response.total || 0;
          // 提取所有定制师的userId到数组（关键步骤）
          this.designerIdsArray = this.designerList.map(designer => designer.userId);
          console.log(this.designerIdsArray)
          this.designerLoading = false;
        })
        .catch(() => {
          this.designerLoading = false;
          this.designerIdsArray = []; // 异常时清空数组
        });
    },
    // 哪种角色可以看到编辑按钮
    showEditButton(row) {
      const role = this.currentUserRoleName
      const designerId = row.designerId
      // 超级管理员总能看到
      if (role === '超级管理员') return true

      //没有分配定制师咨询的客服可以修改
      if (role === '客服') {
        return !this.designerIdsArray.includes(designerId);
      }
      return false
    },

    showRejectButton(row) {
      const role = this.currentUserRoleName
      const designerId = row.designerId
      // 超级管理员总能看到
      if (role === '超级管理员') return true

      //没有分配定制师咨询的客服可以修改
      if (role === '定制师') {
        return this.designerIdsArray.includes(designerId);
      }
      return false
    },

    showAssignDesignerButton() {
      const role = this.currentUserRoleName
      // 超级管理员总能看到
      if (role === '超级管理员') return true

      //没有分配定制师咨询的客服可以修改
      if (role === '客服') return true
      return false
    },

    showAssignDesigner1Button(row) {
      const role = this.currentUserRoleName
      const designerId = row.designerId
      // 超级管理员总能看到
      if (role === '超级管理员') return true

      //没有分配定制师咨询的客服可以修改
      if (role === '客服') {
        return !this.designerIdsArray.includes(designerId);
      }
      return false
    },


    showReject1Button() {
      const role = this.currentUserRoleName
      // 超级管理员总能看到
      if (role === '超级管理员') return true

      //没有分配定制师咨询的客服可以修改
      if (role === '定制师') {
        return true
      }
      return false
    },


    handleUserCurrentChange(currentRow) {
      this.selectedUser = currentRow;
    },
    handleUserRowClick(row) {
      // 点击已选中的行则取消选中
      if (this.selectedUser && this.selectedUser.clientId === row.clientId) {
        this.selectedUser = null;
        this.$refs.userTable.setCurrentRow(null);  // 取消高亮
      } else {
        this.selectedUser = row;
        this.$refs.userTable.setCurrentRow(row);  // 高亮当前行
      }
    },
    handleDesignerCurrentChange(currentRow) {
      this.selectedDesigner = currentRow;
    },
    handleDesignerRowClick(row) {
      // 点击已选中的行则取消选中
      if (this.selectedDesigner && this.selectedDesigner.userId === row.userId) {
        this.selectedDesigner = null;
        this.$refs.designerTable.setCurrentRow(null);  // 取消高亮
      } else {
        this.selectedDesigner = row;
        this.$refs.designerTable.setCurrentRow(row);  // 高亮当前行
      }
    },
    getList() {
      this.loading = true;
      listConsult(this.queryParams).then(async response => {
        const rows = response.rows || [];
        this.total = response.total || 0;

        // 1. 收集已分配的 designerId
        const designerIds = [
          ...new Set(rows.filter(r => r.designerId).map(r => r.designerId))
        ];
        if (designerIds.length) {
          // 2. 批量查询定制师信息
          const { rows: users } = await listRoleUser({
            userIds: designerIds.join(','),
            'roles[0].roleName': '定制师'
          });
          const nameMap = Object.fromEntries(
            (users || []).map(u => [u.userId, u.nickName])
          );
          // 3. 回填 designerName
          rows.forEach(r => {
            r.designerName = nameMap[r.designerId] || null;
          });
        }

        this.consultList = rows;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    getClientList() {
      this.clientLoading = true;  // 开启加载状态
      listClient(this.clientQueryParams).then(response => {  // 传入客户查询参数
        this.clientList = response.rows;  // 客户列表数据
        this.clientTotal = response.total;  // 客户总数（用于分页）
        this.clientLoading = false;  // 关闭加载状态
      }).catch(() => {
        this.clientLoading = false;
      });
    },

    getUserList() {
      this.userLoading = true;
      listUser(this.userQueryParams).then(response => {
        this.userList = response.rows;
        this.userTotal = response.total;
        this.userLoading = false;
      }).catch(() => {
        this.userLoading = false;
      });
    },

    openUserDialog() {
      this.selectedUser = null;
      this.userDialogVisible = true;
      this.getUserList();
    },

    openDesignerDialog(consultId) {  // 接收单个ID参数（可选）
      // 处理目标ID：单个分配用[consultId]，批量分配用已选中的ids
      const targetIds = consultId ? [consultId] : this.ids;

      if (targetIds.length === 0) {
        this.$message.warning("请先选择需要分配定制师的咨询记录");
        return;
      }

      // 检查是否有已分配定制师的记录（避免重复分配）
      const selectedRecords = this.consultList.filter(item => targetIds.includes(item.consultId));
      const assignedRecords = selectedRecords.filter(record => record.designerId !== null);

      if (assignedRecords.length > 0) {
        const consultNumbers = assignedRecords.map(record => record.consultNumber).join(', ');
        this.$message.error(`咨询号 ${consultNumbers} 已经分配定制师，无法重复分配`);
        return;
      }

      // 保存当前需要分配的ID列表（用于后续确认）
      this.currentAssignIds = targetIds;  // 在data中新增currentAssignIds: []
      this.selectedDesigner = null;  // 重置选中的定制师
      this.designerDialogVisible = true;
      this.getDesignerList();  // 加载定制师列表
    },

    /** 退回功能实现 */
    // 修改handlerReject方法，支持接收单个consultId参数
    handlerReject(consultId) {
      // 1. 确定目标ID列表（支持单选/多选）
      const targetIds = consultId ? [consultId] : this.ids;

      if (targetIds.length === 0) {
        this.$message.warning("请先选择需要退回的咨询记录");
        return;
      }

      // 2. 检查未分配的记录（保持不变）
      const selectedRecords = this.consultList.filter(item => targetIds.includes(item.consultId));
      const unassignedRecords = selectedRecords.filter(record => record.designerId === null);
      if (unassignedRecords.length > 0) {
        const consultNumbers = unassignedRecords.map(record => record.consultNumber).join(', ');
        this.$message.error(`咨询号 ${consultNumbers} 尚未分配定制师，无法退回`);
        return;
      }

      // 3. 提取咨询号和当前定制师（保持不变）
      const consultNumbers = selectedRecords.map(record => record.consultNumber).join(', ');
      const currentDesigners = selectedRecords.map(record => record.designerName || '未知定制师').join(', ');

      // 4. 关键：创建纯净的数组副本（去除响应式属性）
      const pureIds = [...targetIds]; // 用扩展运算符创建纯净副本（非响应式）

      // 5. 确认弹窗并调用接口
      this.$modal.confirm(`确定要将咨询号 ${consultNumbers}（当前定制师：${currentDesigners}）退回吗？`).then(() => {
        // 传递纯净的参数对象
        assignDesigner({
          consults: pureIds, // 纯净数组
          designerId: -1     // 退回标识
        }).then(response => {
          this.$modal.msgSuccess("退回成功");
          this.getList();
        }).catch(error => {
          this.$message.error("退回失败: " + (error.response?.data?.msg || error.message));
        });
      });
    },


    confirmUserSelection() {
      if (!this.selectedUser) {
        this.$message.warning("请选择一个用户");
        return;
      }
      this.form.clientName = this.selectedUser.clientName;
      this.form.clientTel = this.selectedUser.clientTel;
      this.form.clientId = this.selectedUser.clientId;
      this.userDialogVisible = false;
    },

    confirmDesignerAssignment() {
      if (!this.selectedDesigner) {
        this.$message.warning("请选择一个定制师");
        return;
      }

      // 使用保存的目标ID列表（单个或批量）
      const targetIds = this.currentAssignIds;

      // 获取选中记录的咨询号和定制师信息
      const selectedRecords = this.consultList.filter(item => targetIds.includes(item.consultId));
      const consultNumbers = selectedRecords.map(record => record.consultNumber).join(', ');
      const designerName = this.selectedDesigner.nickName;

      // 确认弹窗（与退回风格一致）
      this.$modal.confirm(`确定要给咨询号 ${consultNumbers} 分配 ${designerName} 为定制师吗？`).then(() => {
        // 传递纯净数组参数
        const pureIds = [...targetIds];  // 去除响应式属性
        assignDesigner({
          consults: pureIds,
          designerId: this.selectedDesigner.userId
        }).then(response => {
          this.$modal.msgSuccess("分配成功");
          this.designerDialogVisible = false;
          this.getList();  // 刷新列表
        }).catch(error => {
          this.$message.error("分配失败: " + (error.response?.data?.msg || error.message));
        });
      });
    },

    resetUserQuery() {
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        phonenumber: null
      };
      this.getUserList();
    },

    resetClientQuery() {
      this.clientQueryParams = {
        pageNum: 1,
        pageSize: 10,
        clientName: null,  // 客户姓名
        clientTel: null    // 客户手机号
      };
      this.getClientList();  // 重置后重新加载客户列表
    },

    resetDesignerQuery() {
      this.designerQueryParams = {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        phonenumber: null,
        "roles[0].roleName": '定制师'
      };
      this.getDesignerList();
    },

    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.form = {
        consultId: null,
        consultNumber: null,
        clientId: null,
        clientName: null,
        clientTel: null,
        travelerCount: null,
        preferredDestination: null,
        estimatedTime: null,
        flexibleDays: null,
        plannedDays: null,
        budget: null,
        designerId: null,
        remark: null
      };
      this.isEdit = false;
      this.resetForm("form");
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams['travelClient.clientTel'] = null;
      this.queryParams['travelClient.clientName'] = null;
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.consultId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加咨询管理";
    },

    handleUpdate(row) {
      this.reset();
      const consultId = row.consultId || this.ids[0];
      getConsult(consultId).then(response => {
        this.form = response.data;
        this.form.clientName = response.data.travelClient?.clientName || '';
        this.form.clientTel = response.data.travelClient?.clientTel || '';
        this.form.clientId = response.data.clientId;
        this.open = true;
        this.title = "修改咨询管理";
        this.isEdit = true;
      });
    },

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.consultId) {
            updateConsult(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConsult(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    handleDelete(row) {
      const consultIds = row.consultId || this.ids;
      this.$modal.confirm(`是否确认删除咨询管理编号为"${consultIds}"的数据项？`).then(() => {
        return delConsult(consultIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    handleExport() {
      this.download('travel/consult/export', { ...this.queryParams }, `consult_${new Date().getTime()}.xlsx`);
    },

    handleDesigner() {
      this.openDesignerDialog();
    }
  }
};
</script>
<style>
/* 隐藏单选框的文字标签（统一设置） */
.el-radio__label {
  display: none !important;
}
</style>


























































































































